package com.whzjkj.gateway.server.codce;

import com.whzjkj.gateway.constant.JT808Constant;
import com.whzjkj.gateway.util.ByteUtils;
import com.whzjkj.gateway.util.JT808ProtocolUtils;
import com.whzjkj.gateway.vo.PackageData;
import com.whzjkj.gateway.vo.ServerCommonRespondBody;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Arrays;

/**
 * @description: JT808消息编码
 * @author: Mr.Hu
 * @create: 2018-10-31 15:12
 **/
@Component
public class JT808MessageEncoder {


    /**
     * 生成平台通用应答消息
     * @param req
     * @param respondBody
     * @param flowNo
     * @return
     * @throws IOException
     */
    public static byte[] encoderServerCommonRespondMessage(PackageData req, ServerCommonRespondBody respondBody, int flowNo) throws IOException {

        //1. 标识位
        //2. 消息头
        //3. 消息体
        //4. 校验码
        //5. 标识位
        byte[] messageBody = ByteUtils.concatBytes(Arrays.asList(ByteUtils.integerTo2Byte(respondBody.getRespondFlowNo()),
                ByteUtils.integerTo2Byte(respondBody.getRespondMessageId()),
                new byte[]{respondBody.getRespondCode()}
                ));
        int messageBodyProperty = JT808ProtocolUtils.generateMessageBodyProperty(messageBody.length, 0, false, 0);
        byte[] messageHander = JT808ProtocolUtils.generateMessageHeader(JT808Constant.CMD_COMMON_SERVER_RESPOND, messageBodyProperty, req.getMessageHeader().getTerminalPhone(), flowNo);
        //生成校验码
        byte[] messageHanderAndBody = ByteUtils.concatBytes(messageHander,messageBody);
        int checkCode = ByteUtils.mathCheckCode(messageHanderAndBody, 0, messageHanderAndBody.length-1);

        return encode(ByteUtils.concatBytes(messageHander, messageBody, ByteUtils.integerTo1Byte(checkCode)));
    }

    public static byte[] encode(byte[] data) throws IOException {
        //转译消息
        byte[] messsageBytes = JT808ProtocolUtils.translationSend(data);
        byte[] tmp = new byte[messsageBytes.length+2];
        System.arraycopy(messsageBytes, 0, tmp, 1, tmp.length-2);

        tmp[0] = JT808Constant.PACKAGE_MARKER;
        tmp[tmp.length-1] = JT808Constant.PACKAGE_MARKER;
        return tmp;
    }
}
